package com.ochnas.volunteersignup.ui;

import java.io.IOException;
import java.util.List;
import java.util.SortedMap;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ochnas.volunteersignup.domain.FilledVolunteerRequisition;
import com.ochnas.volunteersignup.domain.Position;
import com.ochnas.volunteersignup.domain.TimeSlot;
import com.ochnas.volunteersignup.domain.User;
import com.ochnas.volunteersignup.service.EventService;
import com.ochnas.volunteersignup.service.UserService;
import com.ochnas.volunteersignup.service.VolunteerService;


public class GetPositionService extends HttpServlet {
    WebApplicationContext spring;
    private static final long serialVersionUID = -2560989072138239258L;

    public void init(ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);
        spring = WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EventService eventService = (EventService) spring.getBean("eventService");
        VolunteerService volunteerService = (VolunteerService) spring.getBean("volunteerService");
        UserService userService = (UserService) spring.getBean("userService");
        
        // No id specified - return a list of all positions
        if (request.getRequestURI().endsWith("/") || request.getRequestURI().endsWith("position")) {
            Document doc = DocumentFactory.getInstance().createDocument();
            Element root = doc.addElement("positions");
            List<Position> positions = eventService.findAllPositions();
            for (Position position : positions) {
                root.addElement("position").addAttribute("ref", request.getRequestURL()+"/"+position.getId());
            }

            response.getOutputStream().println(doc.asXML());
        }

        // If an id was specified, look up that item
        else {
            String id = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/")+1);
            Position position = eventService.findPosition(Long.parseLong(id));
            SortedMap<Long, List<FilledVolunteerRequisition>> mapOfTimeSlotVolunteers =  volunteerService.findVolunteersForTimeSlotsByPosition(position.getId());
            SortedMap<Long, List<FilledVolunteerRequisition>> mapOfPositionVolunteers =  volunteerService.findVolunteersForPositionWithoutTimeSlots(position.getId());
            
            Document xmlResponse = DocumentFactory.getInstance().createDocument();
            Element positionElement = xmlResponse.addElement("position");
            positionElement.addAttribute("id", String.valueOf(position.getId()));
            positionElement.addElement("name")
            	.addText(position.getName());
            positionElement.addElement("description")
            	.addText((position.getDescription()==null?"":position.getDescription()));
            positionElement.addElement("requiredNumberOfVolunteers")
            	.addText(String.valueOf(position.getRequiredNumberOfVolunteers()));
            
            Element eventElement = positionElement.addElement("event")
            	.addAttribute("id", String.valueOf(position.getEvent().getId()));
            List<TimeSlot> timeSlots = position.getTimeSlots();
            for (TimeSlot t: timeSlots) {
            	Element timeSlotElement = positionElement.addElement("timeslot")
            		.addAttribute("id", String.valueOf(t.getId()));
            	timeSlotElement.addElement("quantityOfVolunteers")
            		.addText(String.valueOf(t.getQuantityOfVolunteers()));
        		Element tsPosition = timeSlotElement.addElement("position")
        			.addAttribute("id", String.valueOf(t.getPosition().getId()));
        		Element startTime = timeSlotElement.addElement("time")
        			.addAttribute("name", "startTime");
        		startTime.addElement("hourOfDay")
        			.addText(String.valueOf(t.getStartTime().getHourOfDay()));
        		startTime.addElement("minutes")
        			.addText(String.valueOf(t.getStartTime().getMinutes()));
        		
        		Element endTime = timeSlotElement.addElement("time")
        			.addAttribute("name", "endTime");
        		endTime.addElement("hourOfDay")
        			.addText(String.valueOf(t.getEndTime().getHourOfDay()));
        		endTime.addElement("minutes")
        			.addText(String.valueOf(t.getEndTime().getMinutes()));
        		
        		if (mapOfTimeSlotVolunteers.containsKey(t.getId())) {
        			List<FilledVolunteerRequisition> volunteers = mapOfTimeSlotVolunteers.get(t.getId());
					for (FilledVolunteerRequisition v: volunteers) {
						User u = userService.findUserAccount(v.getUser().getId());
		    
		            		
						Element userElement = timeSlotElement.addElement("user")
								.addAttribute("role", "volunteer")
								.addAttribute("id", String.valueOf(u.getId()));

						Element emailElement = userElement
								.addElement("emailAddress");
						emailElement.addText(String
								.valueOf(u.getEmailAddress()));

						Element fNameElement = userElement
								.addElement("firstName");
						fNameElement.addText(String.valueOf(u.getFirstName()));

						Element lNameElement = userElement
								.addElement("lastName");
						lNameElement.addText(String.valueOf(u.getLastName()));

						Element phoneElement = userElement
								.addElement("contactPhoneNumber");
						phoneElement.addText(String.valueOf(u
								.getContactPhoneNumber()));
        			
	        		}
	            }
            }
            if (timeSlots.isEmpty()) {
            	List<FilledVolunteerRequisition> volunteers = mapOfPositionVolunteers.get(position.getId());
				for (FilledVolunteerRequisition v: volunteers) {
					User u = userService.findUserAccount(v.getUser().getId());
	    
	            		
					Element userElement = positionElement.addElement("user")
							.addAttribute("role", "volunteer")
							.addAttribute("id", String.valueOf(u.getId()));

					Element emailElement = userElement
							.addElement("emailAddress");
					emailElement.addText(String
							.valueOf(u.getEmailAddress()));

					Element fNameElement = userElement
							.addElement("firstName");
					fNameElement.addText(String.valueOf(u.getFirstName()));

					Element lNameElement = userElement
							.addElement("lastName");
					lNameElement.addText(String.valueOf(u.getLastName()));

					Element phoneElement = userElement
							.addElement("contactPhoneNumber");
					phoneElement.addText(String.valueOf(u
							.getContactPhoneNumber()));	
				}
            }
            response.setContentType("text/xml");
            response.getOutputStream().println(xmlResponse.asXML());
        }
    }
}
